package com.ph.seata.storage.service.impl;

import com.ph.seata.storage.dto.CommodityDTO;
import com.ph.seata.storage.model.StorageDO;
import com.ph.seata.storage.mapper.StorageMapper;
import com.ph.seata.storage.service.StorageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ph.web.common.response.WrapperResponse;
import io.seata.spring.annotation.GlobalLock;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author swallow
 * @since 2021-06-29
 */
@Service
public class StorageServiceImpl extends ServiceImpl<StorageMapper, StorageDO> implements StorageService {

    @Override
    @GlobalTransactional
    public WrapperResponse<Object> decreaseStorage(CommodityDTO commodityDTO) {
        int storage = baseMapper.decreaseStorage(commodityDTO.getCommodityCode(), commodityDTO.getCount());
        if(storage > 0) {
            return WrapperResponse.buildSuccess();
        }
        return WrapperResponse.buildError("扣减失败");
    }

    public WrapperResponse<StorageDO> loadObject(CommodityDTO commodityDTO) {
        return WrapperResponse.buildSuccess(baseMapper.selectById(commodityDTO.getId()));
    }

    public WrapperResponse<StorageDO> loadObjectForUpdate(CommodityDTO commodityDTO) {
        return WrapperResponse.buildSuccess(baseMapper.loadById(commodityDTO.getId()));
    }

    public WrapperResponse<StorageDO> loadObjectAndGlobalLockForUpdate(CommodityDTO commodityDTO) {
        return WrapperResponse.buildSuccess(baseMapper.loadById(commodityDTO.getId()));
    }

    public WrapperResponse<StorageDO> loadObjectAndGlobalTransactionalForUpdate(CommodityDTO commodityDTO) {
        return WrapperResponse.buildSuccess(baseMapper.loadById(commodityDTO.getId()));
    }


    @GlobalLock
    @Transactional(rollbackFor = {Throwable.class})
    public WrapperResponse<StorageDO> loadObjectAndGlobalLock(CommodityDTO commodityDTO) {
        return WrapperResponse.buildSuccess(baseMapper.selectById(commodityDTO.getId()));
    }

    @GlobalTransactional
    public WrapperResponse<StorageDO> loadObjectAndGlobalTransactional(CommodityDTO commodityDTO) {
        return WrapperResponse.buildSuccess(baseMapper.selectById(commodityDTO.getId()));
    }
}
